package com.chasmcity.munrobagging.data;

import com.chasmcity.munrobagging.model.LatLong;
import com.chasmcity.munrobagging.model.MapReference;
import com.chasmcity.munrobagging.model.Munro;
import com.chasmcity.munrobagging.model.Section;
import com.chasmcity.munrobagging.model.Type;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO: Missing class description for MunroCsvReader!
 * <p>
 * &copy; Copyright 2010 Kizoom Ltd.
 * <p>
 * $Id: wildebeest_standard.epf,v 1.9 2007/01/17 14:59:59 danf Exp $
 */
public class MunroCsvReader {
	
	private static final String CSV_FILE = "cleaned_munros.csv";
	
	private enum Column {
		CODE, ZONE, EAST, NORTH, SHORT_NAME, SECT, NO, TOP, MUNRO, HEIGHT, TYPE, FULL_EASTING, FULL_NORTHING, LONG_NAME, LATITUDE, LONGITUDE;
		
		String asString(String[] items) {
			return items[ordinal()].trim();
		}
		
		int asInt(String[] items) {
			return Integer.parseInt(asString(items));
		}

		double asDouble(String[] items) {
			return Double.parseDouble(asString(items));
		}
	}

	public List<Munro> read() throws IOException {
		List<Munro> munros = new ArrayList<Munro>();
		InputStream inputStream = getClass().getResourceAsStream(CSV_FILE);
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			
			String line = reader.readLine(); // header, ignore
			while ((line = reader.readLine()) != null) {
				String[] items = line.split(",");
				
				Munro munro = new Munro();
				munro.setCode(Column.CODE.asString(items));
				munro.setSection(Section.values()[Column.SECT.asInt(items)]);
				munro.setHeightInMetres(Column.HEIGHT.asInt(items));
				munro.setLatLong(new LatLong(Column.LATITUDE.asDouble(items), Column.LONGITUDE.asDouble(items))); 
				munro.setName(Column.LONG_NAME.asString(items));
				
				munro.setMapReference(new MapReference(
						Column.ZONE.asString(items),
						Column.EAST.asInt(items),
						Column.NORTH.asInt(items)
				));
				
				String type = Column.TYPE.asString(items);
				if (type.equals("M")) {
					munro.setType(Type.MUNRO);
				} else if (type.equals("T")) {
					munro.setType(Type.TOP);
				} else if (type.equals("X")) {
					munro.setType(Type.OTHER);
				}
				
				munros.add(munro);
			}
			
			return munros;
			
		} finally {
			inputStream.close();
		}
	}
}
